package com.ruicar.afs.cloud.contract.gateway.util;

import lombok.extern.slf4j.Slf4j;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

@Slf4j
public final class JavaScriptUtils {

    public static String runPostScript(String response,String jsScript) throws ScriptException {
        try {
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("javascript");
            String script = "function init(val){return JSON.parse(val)};function toStr(obj){ return JSON.stringify(obj) };";
            engine.eval(script+jsScript);
            Invocable inv = (Invocable) engine;
            Object initObj = inv.invokeFunction("init", response);
            Object result =  inv.invokeFunction("convert", initObj);
            Object rtn = inv.invokeFunction("toStr", result);
            log.info("执行结果{}",rtn.toString());
            return rtn.toString();
        }catch (Exception e){
            log.error("js执行失败,返回原始值",e);
            return response;
        }
    }
}
